// 微信 api 封装
export const WXNavigateTo = (url, events) => {
  return new Promise((resolve, reject) => {
    wx.navigateTo({
      url,
      events,
      success: function (res) {
        resolve(res)
      },
      fail: function (err) {
        reject(err)
      }
    })
  })
}

export const WXSwitchTab = url => {
  return new Promise((resolve, reject) => {
    wx.switchTab({
      url,
      success: function (res) {
        resolve(res)
      },
      fail: function (err) {
        reject(err)
      }
    })
  })
};

export const WXRedirectTo = url => {
  return new Promise((resolve, reject) => {
    wx.redirectTo({
      url,
      success: function (res) {
        resolve(res)
      },
      fail: function (err) {
        reject(err)
      }
    })
  })
};

export const WXNavigateBack = delta => {
  return new Promise((resolve, reject) => {
    wx.navigateBack({
      delta,
      success: function (res) {
        resolve(res)
      },
      fail: function (err) {
        reject(err)
      }
    })
  })
};


export const WXReLaunch = url => {
    return new Promise((resolve, reject) => {
        wx.reLaunch({
            url,    
            success: function (res) {
                resolve(res)
            },
            fail: function (err) {
                reject(err)
            }
        })
    })
};

export const WXshowToast = (title) => {
  return new Promise((resolve, reject) => {
    wx.showToast({
      title,
      icon: 'none',
      duration: 2000,
      mask: true,
      success: function (res) {
        resolve(res)
      },
      fail: function (err) {
        reject(err)
      }
    });
  })
};

export const WXGetSystemInfo = () => {
  return new Promise((resolve, reject) => {
    wx.getSystemInfo({
      success: function (res) {
        resolve(res)
      },
      fail: function (err) {
        reject(err)
      }
    })
  })
}

export const WXShowToast = (title, options) => {
  return new Promise((resolve, reject) => {
    wx.showToast({
      icon: 'none',
      title,
      duration: 2000,
      mask: true,
      success: function (res) {
        resolve(res)
      },
      fail: function (err) {
        reject(err)
      },
      ...options
    })
  })
}



export const WXShowModal = (title, content, options) => {
  return new Promise((resolve, reject) => {
    wx.showModal({
      title,
      content,
      success: function (res) {
        resolve(res)
      },
      fail: function (err) {
        reject(err)
      },
      ...options
    })
  })
}

export const WXShowActionSheet = (itemList) => {
  return new Promise((resolve, reject) => {
    wx.showActionSheet({
      itemList,
      success: function (res) {
        resolve(res)
      },
      fail: function (err) {
        reject(err)
      }
    })
  })
}


let ajaxTimes = 0;
export const request = ({ url, ...params }) => {
  console.log(url)
  // console.log(...params)
     wx.showLoading({
         title: "加载中",
         mask: true
     });
      ajaxTimes++;
  const token = wx.getStorageSync('token');

  return new Promise((resolve, reject) => {
    wx.request({
      url,
      header: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`
      },
      ...params,
      success: res => {
        console.log(res.data)
        if (res.data.code === 200) {
          
          resolve(res);
        } else if (res.statusCode === 401) {
          WXShowToast('请登录')
          WXNavigateTo('/pages/login/login')
        } else{
            resolve(res);
        }
      },
      fail: err => {
        reject(err);
      },
      complete: () => { // 失败成功都会执行的函数
          ajaxTimes--;
          if (ajaxTimes === 0) {
              //  关闭正在等待的图标
              wx.hideLoading();
          }
      }
    });
  });
};

// helper 
export const checkPhone = phone => /^1[3456789]\d{9}$/.test(phone);

export const checkEmptyStr = val => val.trim().length === 0;

/**
 * scroll-view 必须设置高度。 占据剩余高度，高度计算函数
 * @param {Array} selectorList 初始时，选择器仅选取页面范围的节点
 * @param {Component} component 初始时，选择器仅选取页面范围的节点
 * @param {Number} otherHeight 其他已知高度 px
 * @return 高度值(px)
 */
export function calcScrollViewHeight(selectorList, component, otherHeight) {
  let windowHeight = 0
  let scrollViewHeight = 0

  return new Promise((resolve, reject) => {
    // 先取出页面高度 windowHeight
    WXGetSystemInfo().then(res => {
      windowHeight = res.windowHeight
    }).then(() => {
      scrollViewHeight = typeof otherHeight === 'number' ? windowHeight - otherHeight : windowHeight
      // 然后取出navbar和header的高度
      // 根据文档，先创建一个SelectorQuery对象实例
      let query = wx.createSelectorQuery().in(component);
      // 然后逐个取出navbar和header的节点信息
      // 选择器的语法与jQuery语法相同

      selectorList.forEach(selector => {
        query.select(selector).boundingClientRect();
      })

      // 执行上面所指定的请求，结果会按照顺序存放于一个数组中，在callback的第一个参数中返回
      query.exec((res) => {
        if (!res[0]) return
        res.forEach(item => {
          scrollViewHeight -= item.height
        })
        resolve(scrollViewHeight)
      });
    }).catch(err => {
      reject(err)
    })
  })
}

export function stickyBottom(el) {
  let windowHeight = 0

  return new Promise((resolve, reject) => {
    WXGetSystemInfo().then(res => {
      windowHeight = res.windowHeight
    })
  })
}